import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hong_vpn_new_20240626/hvn_tools/vpn_manager.dart';
import 'package:hong_vpn_new_20240626/ui/chat/chat.dart';
import 'package:hong_vpn_new_20240626/ui/connect_state/connect_state.dart';
import 'package:hong_vpn_new_20240626/ui/index/location_btn.dart';
import 'package:hong_vpn_new_20240626/utils/configs/color_config.dart';
import 'package:hong_vpn_new_20240626/utils/configs/text_style_config.dart';
import 'package:hong_vpn_new_20240626/utils/customs/zz_button.dart';
import 'package:hong_vpn_new_20240626/utils/global.dart';
import 'package:hong_vpn_new_20240626/utils/utils.dart';
import 'package:hong_vpn_new_20240626/utils/zz_navigator.dart';

import '../../utils/customs/app_webview.dart';

class IndexWidget extends StatefulWidget {
  const IndexWidget({super.key});

  @override
  State<IndexWidget> createState() => _IndexWidgetState();
}

class _IndexWidgetState extends State<IndexWidget> {
  StreamSubscription? stream;

  /// 当前操作是否是链接VPN
  late bool _isConnectingVpn = false;
  late bool _isDisConnectingVpn = false;
  @override
  void initState() {
    super.initState();
    stream = eventBus.on<VPNStatus>().listen((event) {
      zzLog("VPN Status = ${event.status.title}");
      if (!mounted) {
        return;
      }
      setState(() {});

      if (_isConnectingVpn) {
        if (Global.ovpnStatus.status == OvpnStatus.connected) {
          _isConnectingVpn = false;
          // _connectedAd.reloadAd();
          // _nativeAd.reloadAd();
          mounted
              ? ZZNavigator.push(
                  widget: const ConnectedStatusWidget(
                  isSuc: true,
                  connectStatusValue: "Connected",
                ))
              : null;
        } else if (Global.ovpnStatus.status == OvpnStatus.error) {
          _isConnectingVpn = false;
          mounted
              ? ZZNavigator.push(
                  widget: const ConnectedStatusWidget(
                  isSuc: false,
                  connectStatusValue: "Connected Failed",
                ))
              : null;
        }
      } else if (_isDisConnectingVpn) {
        if (Global.ovpnStatus.status == OvpnStatus.disconnected) {
          _isDisConnectingVpn = false;
          mounted
              ? ZZNavigator.push(
                  widget: const ConnectedStatusWidget(
                  isSuc: false,
                  connectStatusValue: "Disconnected",
                ))
              : null;
        } else if (Global.ovpnStatus.status == OvpnStatus.error) {
          _isDisConnectingVpn = false;
          mounted
              ? ZZNavigator.push(
                  widget: const ConnectedStatusWidget(
                  isSuc: false,
                  connectStatusValue: "Disconnected Failed",
                ))
              : null;
        }
      }
    });
    if (!Global.isReadPrivacy) {
      // 首次进入阅读 隐私条款
      Global.isReadPrivacy = true;
      Timer.periodic(const Duration(seconds: 1), (timer) {
        timer.cancel();
        ZZNavigator.push(
          widget: AppWebWidget(
            Global.privacyUrl,
            title: "Privacy Policy",
            isShowBottomAction: false,
          ),
        );
      });
    }
  }

  @override
  void dispose() {
    stream?.cancel();
    super.dispose();
  }

  connectTap() {
    if (Global.ovpnStatus.status == OvpnStatus.disconnected ||
        Global.ovpnStatus.status == OvpnStatus.error) {
      _isConnectingVpn = true;
      _isDisConnectingVpn = false;
      VpnManager.share.connect();
      return;
    }
    if (Global.ovpnStatus.status == OvpnStatus.connected) {
      _isDisConnectingVpn = true;
      _isConnectingVpn = false;
      VpnManager.share.disconnect();
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Network"),
        // actions: [
        //   IconButton(
        //       onPressed: () => ZZNavigator.push(widget: const SettingWidget()),
        //       icon: const Icon(Icons.settings))
        // ],
      ),
      body: SafeArea(
          child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const AspectRatio(aspectRatio: 7),
          Image.asset(
              Global.ovpnStatus.status == OvpnStatus.connected
                  ? "assets/images/按钮.png"
                  : "assets/images/2.0x/按钮2.png",
              width: 160),
          const LocationBtnWidget(),
          // _spaceLine(),
          // IndexActionBtnWidget(
          //   title: "Live Chat",
          //   image: Image.asset("assets/images/聊天 .png", width: 40),
          //   onTap: () => ZZNavigator.push(widget: const ChatWidget()),
          // ),
          // _spaceLine(),
          // IndexActionBtnWidget(
          //   title: "Scan QR",
          //   image: Image.asset("assets/images/扫一扫.png", width: 40),
          //   onTap: () => ZZNavigator.push(widget: const ScanQRWidget()),
          // ),
          // _spaceLine(),
          ZZButton(
            onTap: () => connectTap(),
            height: 44,
            width: 160.w,
            mainAxisAlignment: MainAxisAlignment.center,
            title: Text(Global.ovpnStatus.status.connectTitle,
                style: TextStyleConfig.bold.size(16)),
            decoration: BoxDecoration(
                color: Global.ovpnStatus.status.statusBgColor,
                borderRadius: const BorderRadius.all(Radius.circular(22))),
            margin: const EdgeInsets.all(10),
          ),
          const Spacer(),
          // _chatBtn()
        ],
      )),
    );
  }

  Widget _spaceLine() {
    return Divider(
      height: 0.5,
      endIndent: 35,
      indent: 35,
      thickness: 0,
      color: Colors.white.withOpacity(0.2),
    );
  }

  Widget _chatBtn() {
    return Container(
      width: double.infinity,
      height: 200,
      margin: const EdgeInsets.only(left: 15, right: 15),
      clipBehavior: Clip.hardEdge,
      decoration: const BoxDecoration(
          color: ColorConfig.orange,
          borderRadius: BorderRadius.all(Radius.circular(15))),
      child: Stack(
        fit: StackFit.expand,
        alignment: AlignmentDirectional.bottomCenter,
        children: [
          Image.asset(
            "assets/images/Rectangle 49.png",
            fit: BoxFit.cover,
            alignment: Alignment.topCenter,
          ),
          Positioned(
              height: 44,
              left: 0,
              right: 0,
              child: ZZButton(
                onTap: () => ZZNavigator.push(
                    widget: const ChatWidget(
                  model: null,
                )),
                mainAxisAlignment: MainAxisAlignment.center,
                title: Text("Chat", style: TextStyleConfig.bold.size(22)),
                decoration: const BoxDecoration(
                    color: ColorConfig.orange,
                    borderRadius: BorderRadius.all(Radius.circular(15))),
              )),
        ],
      ),
    );
  }
}
